package ar.edu.unicen.exa.isistan.archassis.view.dialogs;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

import ar.edu.unicen.exa.isistan.archassis.ia.api.AIModuleFacade;
import ar.edu.unicen.exa.isistan.archassis.ia.api.db.ListCases;
import ar.edu.unicen.exa.isistan.archassis.view.Application;
import ar.edu.unicen.exa.isistan.archassis.view.cases.CasesComposite;

public class SelectCaseDialog extends Dialog {

	protected ListCases result;
	protected Shell shell;
	private CasesComposite casesComposite;

	/**
	 * Create the dialog.
	 * @param parent
	 * @param style
	 */
	public SelectCaseDialog(Shell parent) {
		super(parent, 0);
		setText(Application.APPLICATION_NAME + " | Agregar caso");
	}

	/**
	 * Open the dialog.
	 * @return the result
	 */
	public ListCases open() {
		createContents();
		shell.open();
		shell.layout();
		Display display = getParent().getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		return result;
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
		shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.MAX | SWT.RESIZE | SWT.APPLICATION_MODAL);
		shell.setSize(450, 500);
		shell.setText(getText());
		shell.setLayout(new FormLayout());
		
		casesComposite = new CasesComposite(shell, this);
		casesComposite.setCases(AIModuleFacade.getInstance().getAllCases().values());
		
		Button btnNewButton = new Button(shell, SWT.NONE);
		btnNewButton.setText("Cancelar");
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				exitAction(false);
			}
		});
		
		{	
			FormData formData = new FormData();
			formData.bottom = new FormAttachment(100, -5);
			formData.right = new FormAttachment(100, -5);
			btnNewButton.setLayoutData(formData);
		}
		
		{
			FormData fd_composite = new FormData();
			fd_composite.bottom = new FormAttachment(btnNewButton, -5);
			fd_composite.right = new FormAttachment(100, -5);
			fd_composite.top = new FormAttachment(0, 5);
			fd_composite.left = new FormAttachment(0, 5);
			casesComposite.setLayoutData(fd_composite);
		}
		
	}

	protected void exitAction(boolean b) {
		result = null;
		if (b) {
			result = casesComposite.getSelected();
		}
		shell.dispose();
	}
	public void exitCase() {
		exitAction(true);
	}
}
